package helper.request.plan;

import java.sql.SQLException;
import java.text.DateFormat;
import java.util.ArrayList;

import server.dbconnector.DatabaseConnector;

import helper.request.*;
import base.Plan;
import base.User;

public class AddPlanRequest implements PlanRequest, RequestUndo {
	private static final long serialVersionUID = 8378588739908720966L;
	private User currentuser;
	private ArrayList<Plan> planList;
	private Plan clonePlan;
	private Plan plan;

	public AddPlanRequest(User currentuser, Plan plan, ArrayList<Plan> planList) {
		this.currentuser = currentuser;
		this.clonePlan = plan.clone();
		this.plan = plan;
		this.planList = planList;
	}

	@Override
	public Plan getPlan() {
		return clonePlan;
	}

	@Override
	public User getcurrentuser() {
		return currentuser;
	}

	@Override
	public int getcurrentuserid() {
		return currentuser.getid();
	}

	@Override
	public boolean execute() {
		try {
			planList.add(plan);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public boolean de_execute() {
		try {
			planList.remove(plan);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public void process(DatabaseConnector dc) throws SQLException {
		String availstr = "";
		if (this.plan.getavailable() != null)
			for (int i = 0; i < this.plan.getavailable().size(); i++) {
				availstr += this.plan.getavailable().get(i).toString();
				if (i != this.plan.getavailable().size() - 1)
					availstr += ",";
			}
		dc
				.commit("insert into plan(userid,title,content,datetime,level,state,visible,availableto)"
						+ "values("
						+ this.getcurrentuserid()
						+ ","
						+ "'"
						+ this.plan.gettitle()
						+ "','"
						+ this.plan.getcontent()
						+ "','"
						+ DateFormat.getDateInstance().format(
								this.plan.getdate())
						+ "',"
						+ this.plan.getlevel()
						+ ","
						+ this.plan.getState()
						+ "," + this.plan.getVisible() + ",'" + availstr + "')");
	}

}
